package com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectPosition

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable

@Serializable
object SelectPosition

fun NavGraphBuilder.selectPositionDestination(
    padding: PaddingValues = PaddingValues(0.dp),
    navController: NavController
) {
    composable<SelectPosition> {
        val viewModel: SelectPositionViewModel = viewModel()
        val uiState = viewModel.uiState.collectAsStateWithLifecycle().value
        SelectPositionScreen(
            padding = padding,
            uiState = uiState,
            onBack = navController::popBackStack,
            onGetPositionList = viewModel::getPositionList,
            onFilterPosition = viewModel::filterPosition,
            onSelectPosition = {
                CoroutineScope(Dispatchers.IO).launch {
                    SelectPositionEvent.emit(it)
                    withContext(Dispatchers.Main) {
                        navController.popBackStack()
                    }
                }
            }
        )
    }
}

fun NavController.navigateToSelectPosition() {
    navigate(SelectPosition)
}